//
//  FCSharingView.swift
//  miaoyin
//
//  Created by David on 2017/4/22.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class FCSharingView: UIView, TencentSessionDelegate {

    let shareMethod = ["wechat_moment": "朋友圈", "wechat_greenbg": "微信好友", "qq_bluebg": "QQ", "weibo": "微博", "qzone": "QQ空间", "share_link": "复制链接", "safari":"Safari"]
    var shareOrder = ["wechat_moment", "wechat_greenbg", "qq_bluebg", "qzone", "safari", "share_link"]
    var row = 2
    var column = 3
    
    var shareObj:FCSharingObj?
    
    var bgView: UIButton!
    var shareView: UIView!
    var bgHeight: CGFloat!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        alpha = 0
        
        if !WXApi.isWXAppInstalled(){
            shareOrder.remove(at: shareOrder.index(of: "wechat_moment")!)
            shareOrder.remove(at: shareOrder.index(of: "wechat_greenbg")!)
        }
        
        if !UIApplication.shared.canOpenURL(URL(string: "mqq://")!){
            shareOrder.remove(at: shareOrder.index(of: "qq_bluebg")!)
            shareOrder.remove(at: shareOrder.index(of: "qzone")!)
        }
        
        if shareOrder.count == 2 {
            row = 1
        }
        
        bgView = UIButton(frame: frame)
        bgView.backgroundColor = UIColor(white: 0, alpha: 0.6)
        addSubview(bgView)
        bgView.addTarget(self, action: #selector(FCSharingView.closeView), for: .touchUpInside)
        
        bgHeight = (frame.height/6)*CGFloat(row)
        shareView = UIView(frame: CGRect(x: 0, y: frame.height - bgHeight, width: frame.width, height: bgHeight))
        shareView.backgroundColor = UIColor.white
        addSubview(shareView)
        
        let btnHeight = bgHeight/CGFloat(row)
        let btnWidth = frame.width/CGFloat(column)
        
        for i in 0..<shareOrder.count{
            let image = UIImage(named: shareOrder[i])
            let shareName = shareMethod[shareOrder[i]]
            if image != nil && shareName != nil{
                let r = i/column
                let c = i%column
                let btnView = UIView(frame: CGRect(x: CGFloat(c)*(frame.width/CGFloat(column)), y: CGFloat(r)*(bgHeight/CGFloat(row)) + 16, width: btnHeight, height: btnWidth))
                
                let imgBtn = UIButton(frame: CGRect(x: 0, y: 0, width: btnHeight-20-32, height: btnHeight-20-32))
                imgBtn.tag = i
                imgBtn.setImage(image!, for: .normal)
                imgBtn.center.x = btnWidth/2
                btnView.addSubview(imgBtn)
                
                let titleBtn = UIButton(frame: CGRect(x: 0, y: btnHeight-20-20, width: btnWidth, height: 20))
                titleBtn.tag = i
                titleBtn.setTitle(shareName!, for: .normal)
                titleBtn.setTitleColor(themeColor2, for: .normal)
                titleBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
                btnView.addSubview(titleBtn)
                
                imgBtn.addTarget(self, action: #selector(FCSharingView.doShare(btn:)), for: .touchUpInside)
                titleBtn.addTarget(self, action: #selector(FCSharingView.doShare(btn:)), for: .touchUpInside)
                
                shareView.addSubview(btnView)
                
                
            }
        }
        _ = TencentOAuth(appId: "101382009", andDelegate: self)
    }
    
    func openView(shareObj: FCSharingObj?){
        self.shareObj = shareObj
        self.alpha = 1
        self.shareView.center.y = frame.height + bgHeight/2
        self.bgView.alpha = 0
        UIView.animate(withDuration: 0.3) { 
            self.shareView.center.y = self.frame.height - self.bgHeight/2
            self.bgView.alpha = 1
        }
    }
    
    func closeView(){
        self.shareView.center.y = frame.height - bgHeight/2
        self.bgView.alpha = 1
        UIView.animate(withDuration: 0.3, animations: { 
            self.shareView.center.y = self.frame.height + self.bgHeight/2
            self.bgView.alpha = 0
        }) { (finish) in
            self.alpha = 0
        }
    }
    
    func doShare(btn: UIButton){
        switch shareOrder[btn.tag] {
        case "wechat_moment":
            
            let msg = WXMediaMessage()
            msg.title = shareObj?.title ?? "喵印文章"
            msg.description = shareObj?.title ?? "没有描述"
            msg.setThumbImage(shareObj?.thumb ?? UIImage(named: "AppIcon60x60"))
            
            
            let webObj = WXWebpageObject()
            webObj.webpageUrl = shareObj?.url ?? ""
            msg.mediaObject = webObj
            
            let req = SendMessageToWXReq()
            req.bText = false
            req.message = msg
            req.scene = Int32(WXSceneTimeline.rawValue)
            WXApi.send(req)
            break
        case "wechat_greenbg":
            let msg = WXMediaMessage()
            msg.title = shareObj?.title ?? "喵印文章"
            msg.description = shareObj?.title ?? "没有描述"
            msg.setThumbImage(shareObj?.thumb ?? UIImage(named: "AppIcon60x60"))
            
            
            let webObj = WXWebpageObject()
            webObj.webpageUrl = shareObj?.url ?? ""
            msg.mediaObject = webObj
            
            let req = SendMessageToWXReq()
            req.bText = false
            req.message = msg
            req.scene = Int32(WXSceneSession.rawValue)
            WXApi.send(req)
            
            break
        case "qq_bluebg":
            
            let obj = QQApiNewsObject(url: URL(string: shareObj?.url ?? ""), title: shareObj?.title ?? "喵印文章", description: shareObj?.title ?? "没有描述", previewImageData: UIImageJPEGRepresentation(shareObj?.thumb ?? UIImage(named: "AppIcon60x60")!, 0.8), targetContentType: QQApiURLTargetTypeNews)
            let req = SendMessageToQQReq(content: obj)
            let code = QQApiInterface.send(req)
            
            print(code)
            
            break
        case "qzone":
            let obj = QQApiNewsObject(url: URL(string: shareObj?.url ?? ""), title: shareObj?.title ?? "喵印文章", description: shareObj?.title ?? "没有描述", previewImageData: UIImageJPEGRepresentation(shareObj?.thumb ?? UIImage(named: "AppIcon60x60")!, 0.8), targetContentType: QQApiURLTargetTypeNews)
            let req = SendMessageToQQReq(content: obj)
            let code = QQApiInterface.sendReq(toQZone: req)
            print(code)
            break
        case "share_link":
            UIPasteboard.general.string = shareObj?.url
            break
        case "safari":
            if let url = URL(string: shareObj?.url ?? ""){
                UIApplication.shared.openURL(url)
            }
            
            break
        default:
            break
        }
        closeView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func tencentDidLogin() {
        
    }
    func tencentDidNotLogin(_ cancelled: Bool) {
        
    }
    func tencentDidNotNetWork() {
        
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

class FCSharingObj{
    var title: String?
    var description: String?
    var thumb: UIImage?
    var url: String?
    
    init(title: String?, description: String?, thumb: UIImage?, url: String?) {
        self.title = title
        self.description = description
        self.thumb = thumb
        self.url = url
        
    }
}
